package com.example.ricebibackend.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.example.ricebibackend.common.errorcode.ServiceErrorCodeConstants;
import com.example.ricebibackend.common.exception.ServiceException;
import com.example.ricebibackend.service.AIService;
import com.example.ricebibackend.service.dto.AIResponseDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * AI业务逻辑实现类
 * @author ricejson
 */
@Service
public class AIServiceImpl implements AIService {

    @Value("${ali.apikey}")
    private String apiKey;

    @Override
    public AIResponseDTO genAnalysisResultByAI(String csvData, String goal, String chartType) {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是一个专业的数据分析师和前端开发专家,现在我会严格按照如下格式进行输入:\n" +
                        "分析目标:\n" +
                        "{用户输入的分析目标}\n" +
                        "原始数据:\n" +
                        "{用户输入的CSV格式数据，中间使用,作为分隔符}" +
                        "请你用以下固定格式进行返回：\n" +
                        "【【【【【\n" +
                        "{生成图表数据对应的echarts V5版本options配置JSON格式对象}" +
                        "【【【【【\n" +
                        "{对应的分析结论}")
                .build();
        goal += (StringUtils.isNotBlank(chartType) ? ",指定图表类型为" + chartType : "");
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("分析目标:\n" +
                        goal + "\n" +
                        "原始数据:\n" +
                        csvData)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        GenerationResult generationResult = null;
        try {
            generationResult = gen.call(param);
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }
        String resp = generationResult.getOutput().getChoices().get(0).getMessage().getContent();
        if (StringUtils.isBlank(resp)) {
            throw new ServiceException(ServiceErrorCodeConstants.AI_PARSE_ERROR);
        }
        // 进行数据切割
        String[] splitArr = resp.split("【【【【【");
        if (splitArr.length < 3) {
            throw new ServiceException(ServiceErrorCodeConstants.AI_PARSE_ERROR);
        }
        AIResponseDTO aiResponseDTO = new AIResponseDTO();
        aiResponseDTO.setChartData(splitArr[1].trim());
        aiResponseDTO.setAnalysisResult(splitArr[2].trim());
        return aiResponseDTO;
    }
}
